<template>
  <div id="app" :class="{ 'dark': isDarkMode }">
    <router-view />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 主题模式状态
const isDarkMode = ref(false)

// 切换主题模式
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value
  localStorage.setItem('theme-mode', isDarkMode.value ? 'dark' : 'light')
  
  // 更新 body 的 class
  if (isDarkMode.value) {
    document.body.classList.add('dark')
  } else {
    document.body.classList.remove('dark')
  }
}

// 初始化主题
const initTheme = () => {
  // 从 localStorage 获取保存的主题
  const savedTheme = localStorage.getItem('theme-mode')
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
  
  // 优先使用保存的主题，其次使用系统偏好
  isDarkMode.value = savedTheme ? savedTheme === 'dark' : prefersDark
  
  // 应用主题
  if (isDarkMode.value) {
    document.body.classList.add('dark')
  } else {
    document.body.classList.remove('dark')
  }
}

// 监听系统主题变化
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
mediaQuery.addEventListener('change', (e) => {
  // 只有在没有保存过主题设置时才跟随系统
  if (!localStorage.getItem('theme-mode')) {
    isDarkMode.value = e.matches
    if (isDarkMode.value) {
      document.body.classList.add('dark')
    } else {
      document.body.classList.remove('dark')
    }
  }
})

// 暴露切换方法到全局
window.toggleTheme = toggleTheme

onMounted(() => {
  initTheme()
})
</script>

<style>
#app {
  margin: 0;
  padding: 0;
  height: 100vh;
  width: 100vw;
}
</style>
